package org.shiro.config;


import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;
import java.time.Duration;


/** redis配置 集群下启动session共享，需打开@EnableRedisHttpSession 单机下不需要
 * @author LENOVO
 */
// @EnableRedisHttpSession
@Configuration
//系统中有RedisOperations类时
@ConditionalOnClass(RedisOperations.class)
//启动RedisProperties这个类
@EnableConfigurationProperties(RedisProperties.class)
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport implements Serializable {
  @Autowired private RedisTemplate redisTemplate;

  /** 配置缓存管理器 */
  public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration config =
        RedisCacheConfiguration.defaultCacheConfig()
            //                30分钟缓存失效
            .entryTtl(Duration.ofMinutes(30))
            //                设置Key的序列化方式
            .serializeKeysWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                    new StringRedisSerializer()))
            //                设置value的序列化方式
            .serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(
                    new FastJsonRedisSerializer(Object.class)))
            //                不缓存空值
            .disableCachingNullValues();

    return RedisCacheManager.builder(redisConnectionFactory)
        .cacheDefaults(config)
        .transactionAware()
        .build();
  }

  @Bean
  public JedisConnectionFactory jedisConnectionFactory(){
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
    return jedisConnectionFactory;
  }
}
